package com.ldy.core.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldy.core.entity.BaseOrg;
import com.ldy.core.mapper.BaseOrgMapper;
import com.ldy.core.service.BaseOrgService;
import com.ldy.core.util.MySession;

import cn.hutool.core.collection.CollectionUtil;

@Service
public class BaseOrgServiceImpl extends ServiceImpl<BaseOrgMapper, BaseOrg> implements BaseOrgService {

	private static final Logger logger = LoggerFactory.getLogger(BaseOrgServiceImpl.class);

	private static Map<String, BaseOrg> cacheMap = new HashMap<>();

	@PostConstruct
	public void init() {
		try {
			this.refreshCacheOrgs();
		} catch (Exception e) {
			logger.error("初始化机构，缓存异常", e);
		}
	}

	@Override
	public List<String> getSubOrgs(String orgCode) {
		BaseOrg org = cacheMap.get(orgCode);
		List<String> orgCodes = new ArrayList<String>();
		getSubOrgCode(org, orgCodes);
		return orgCodes;
	}

	private void getSubOrgCode(BaseOrg org, List<String> orgCodes) {
		orgCodes.add(org.getId());
		if (CollectionUtil.isNotEmpty(org.getSubOrgs())) {
			for (BaseOrg o : org.getSubOrgs()) {
				getSubOrgCode(o, orgCodes);
			}
		}
	}

	@Async
	@Override
	public void refreshCacheOrgs() {
		QueryWrapper<BaseOrg> query = new QueryWrapper<>();
		List<BaseOrg> list = baseMapper.selectList(query);
		Map<String, BaseOrg> map = new HashMap<>();
		for (BaseOrg org : list) {
			map.put(org.getId(), org);
		}
		for (BaseOrg org : list) {
			BaseOrg baseOrg = map.get(org.getParentId());
			if (baseOrg != null) {				
				baseOrg.getSubOrgs().add(org);
			}
		}
		cacheMap = map;
	}

	@Override
	public List<String> getMySubOrgs() {
		String orgCode = MySession.get().getOrgCode();
		if (!StringUtils.hasText(orgCode)) {
			return null;
		}
		List<String> subOrgs = getSubOrgs(orgCode);
		return subOrgs;
	}

}
